var papers = {
	listData: new Array(),
	state: ["作废", "暂存", "启用", "停用"],
	listQuestion: new Array(),
	questionIds: {},
	searchParamsP: "", // 试卷查询条件
	searchParamsQ: "", // 试题查询条件
	typeMap: {},
	category: ["模拟卷", "真题卷", "随机卷"],
}
$(function() {
	findType();
	$("#state1_edit,#state2_edit,#state3_edit,#state4_edit").button();
	$("#questionBox").dialog({
		width: 500,
		autoOpen: false, // 默认不打开false
		modal: true, // 遮罩效果默认是false不遮住
	});
	$("#questionRandomDialog")
		.dialog({
			width: 400,
			autoOpen: false, // 默认不打开false
			modal: true, // 遮罩效果默认是false不遮住
			buttons: {
				"一键生成": function() {
					toolAction
						.baseXHR(
							"Question/randQuestionByTypeIdClassesNum",
							$(
								"#questionRandomDialog input,#typeId_view input")
							.serialize())
						.done(
							function(data) {
								if(data.baseModel.resultFlag > 0) {
									alert(data.baseModel.message);
								} else {
									var map = data.baseModel.data;
									setRamdomQuestion(map);
									$(
											"#questionRandomDialog")
										.dialog("close");
								}

							});
				},
				"取消": function() {
					$(this).dialog("close");
				}
			},
		});
	$("#classes_search_question").change(function() {
		findQuestionPage()
	});
	$("#listData_question").on(
		"click",
		".chkQuestionItem",
		function() {
			var list = papers.listQuestion[$(this).attr("name")];
			if($(this).prop("checked")) {
				if($("#srore_papersQuestion").val() == "") {
					alert("请填写试题分数");
					$(this).prop("checked", false);
					return;
				}
				var li = $("<li></li>");
				li.append("<label id='qil_" + list.questionId + "'>" +
					list.subject + "</label>");
				li.append("<input name='questionIds' type='hidden' value='" +
					list.questionId + "'>");
				li.append("<input name='scores' type='hidden' value='" +
					$("#srore_papersQuestion").val() + "'>");
				li.append("<label class='scores'>(" +
					$("#srore_papersQuestion").val() + "分)</label>");
				li
					.append("<span class='answer'>" + list.answer +
						"</span>");
				$("#listQuest_" + $("#classes_search_question").val())
					.append(li);
				papers.questionIds[list.questionId] = "1";
			} else {
				$("#qil_" + list.questionId).parent().remove();
				papers.questionIds[list.questionId] = "0";
			}
		});
	$("#btnExp_question").click(
		function() {
			window.location.href = "Papers/expPapers?papersId=" +
				$("#papersId_edit").val();
		});
});

function findDataPage(actionName, cpage) {
	if(actionName == null || actionName == "") {
		actionName = "Papers/findPapersPage";
	}
	advancedQuery.condition = papers.searchParamsP;
	toolAction.findData(actionName, cpage, "#printPage", findDataPage,
		showListData);
}
/**
 * 查询分页列表
 * 
 * @param list
 */
function showListData(list) {
	var node = "#listForm";
	if(setFileInfo.defaultShowListData(list, node)) {
		return;
	}
	papers.listData = list;
	for(var i = 0; i < list.length; i++) {
		var tr = $("<tr onDblClick=showViewData(" + i + ")></tr>");
		tr
			.append("<td class='permissions_delete'><input type='checkbox' class='list-page-content-table-checkboxs' name='ids' value='" +
				list[i].papersId + "' /></td>");
		tr.append("<td>" + validation.processNullData(list[i].code) + "</td>"); // 个人申请编号
		tr.append("<td>" + validation.processNullData(list[i].papersName) +
			"</td>");
		tr.append("<td>" + papers.typeMap[list[i].typeId] + "</td>");
		tr.append("<td>" + papers.category[list[i].category] + "</td>");
		tr.append("<td>" + validation.processNullData(list[i].creator) +
			"</td>");
		tr.append("<td>" + validation.DateDetailInfo(list[i].createDate) +
			"</td>");
		tr.append("<td>" + papers.state[list[i].state] + "</td>");
		var check = "<a class='editIcon' title='查看' href='javascript:;' onclick='showViewData(" +
			i + ")'> <i class='icon-search'></i></a>"; // 查看按钮
		var edit = "<a class='editIcon permissions_update' title='编辑' href='javascript:;' onClick='showEditData(" +
			i + ")'> <i class='icon-edit'></i></a>"; // 编辑按钮
		var remove = "<a class='deleteIcon permissions_delete' title='删除' href='javascript:;' onclick=removeData('" +
			list[i].papersId + "')> <i class='icon-trash'></i></a>";
		tr.append("<td>" + check + edit + remove + "</td>");
		$(node + " tbody").append(tr);

	}
}

function showAddData() {
	$("#submitForm").attr("action", "Papers/addPapers");
	resetData();
}
/**
 * 显示详细信息
 * 
 * @param n
 */
function showViewData(n) {
	resetData();
	var list = papers.listData[n];
	$(".editP").hide();
	$(".viewP").show();
	$("#taskView").click();
	setFileInfo.defaultShowViewData(list, "#submitForm");
	$("#state_view").html(papers.state[list.state]);
	$("#typeId_view").html(papers.typeMap[list.typeId]);
	$("#category_view").html(papers.category[list.category]);
	findPapersQuestionByPapersId(list.papersId);

}
/**
 * 显示修改页面信息
 * 
 * @param n
 */

function showEditData(n) {
	resetData();
	$("#submitForm").attr("action", "Papers/updatePapers");
	var list = papers.listData[n];
	$(".viewP").hide();
	$(".editP").show();
	$("#nextSubmit_btn").hide();
	$("#taskEdit").click();
	setFileInfo.defaultShowEditData(list, "#submitForm");

	$(
		".inputCheckbox input[type='radio'][name='state'][value='" +
		list.state + "']").click();
	findPapersQuestionByPapersId(list.papersId);
	$("#typeParentDialog .li_" + list.typeId).children(".appendNodeP").click(); // 选择当前的类别
}
/**
 * 提交数据
 */
function submitEditData(isNext) {
	if(checkData()) {
		var actionName = $("#submitForm").attr("action");
		var formData = $("#submitForm :input,#submitForm_question :input")
			.serialize();
		toolAction.baseXHR(actionName, formData).done(function(data) {
			if(data.baseModel.resultFlag > 0) {
				alert(data.baseModel.message);
			} else {
				if(isNext == 1) { // 继续添加
					showAddData();
				} else {
					$("#taskList").click(); // 返回列表
				}
			}

		});
	}
}
/**
 * 删除数据
 * 
 * @param id
 */
function removeData(id) {
	var nodeLocation = "#listForm";
	var actionName = "Papers/deletePapers";
	// 设置删除请求，删除的id，批量删除时复选框所在节点，请求路径，查询方法
	toolAction.removeData(id, nodeLocation, actionName, findDataPage);
}
/**
 * 验证提交数据
 * 
 * @returns {Boolean}
 */
function checkData() {
	var flag = true;
	var str = "";
	var papersName_edit = $("#papersName_edit");
	if(!validation.isNull(papersName_edit.val())) {
		str += "试卷名称不能为空\n";
		papersName_edit.focus();
	}
	var typeId_edit = $("#typeId_view input");
	if(typeId_edit.length < 1 || typeId_edit.val() == "") {
		str += "请选择分类\n";
	}
	if(str.length > 0) {
		flag = false;
		alert(str);
	}
	return flag;
}
/**
 * 重置数据
 */
function resetData() {
	$(".viewP").hide();
	$(".editP").show();

	$("#submitForm input[type='text'],textarea").val("");
	$("#state1_edit").click();
	$("#listQuest_0,#listQuest_1,#listQuest_2,#listQuest_3,#listQuest_4")
		.empty();
	$("#category_edit").val("0");
	papers.questionIds = {};
	$("#typeParentDialog").siblings(".ui-dialog-buttonpane").find("button").eq(
		1).click();
}
/**
 * 返回列表
 */
function returnData() {
	setFileInfo.defaultReturnList();
}
/**
 * 快速查询
 */
function searchqData() {
	setFileInfo.defaultSearchParms("#searchqDataBox");
	papers.searchParamsP = advancedQuery.condition;
	findDataPage(); // 查询信息
}
/**
 * 高级查询
 */
function searchData() {
	setFileInfo.defaultSearchParms("#searchDataBox");
	advancedQuery.pageSize = $("#pageSize_search").val();
	papers.searchParamsP = advancedQuery.condition;
	findDataPage(); // 查询信息
}
/**
 * 查询分类
 */
function findType() {

	toolAction.baseAjax("QuestionType/findQuestionType", "").done(
		function(data) {
			var list = data.baseModel.data;
			setSelectBox.typeParentDialog("#typeParentDialog",
				"#typeId_view", "typeId", list, "typeId", "typeName",
				"parentTypeId");
			setSelectBox.typeParentDialog("#typeParentDialog_question",
				"#typeId_search_question", "typeId", list, "typeId",
				"typeName", "parentTypeId");

			if(list != null) {
				for(var i = 0; i < list.length; i++) {
					$("#typeId_search,#typeId_searchq").append(
						"<option value='" + list[i].typeId + "'>" +
						list[i].typeName + "</option");
					papers.typeMap[list[i].typeId] = list[i].typeName;
				}
			}

		});
}
/**
 * 添加
 */
function showAddQuestion() {
	// 试题选择框同步试卷中的分类
	$("#typeParentDialog_question .li_" + $("#typeId_view .appendPh").val())
		.children(".appendNodeP").click(); // 选择当前的类别
	$("#questionBox").dialog("open");
	findQuestionPage();

}
/**
 * 查询试题信息
 * 
 * @param actionName
 * @param cpage
 */
function findQuestionPage(actionName, cpage) {
	if(actionName == null || actionName == "") {
		actionName = "Question/findQuestionPage";
	}
	setFileInfo.defaultSearchParms("#searchQuestionBox");
	toolAction.findData(actionName, cpage, "#printPage_question",
		findQuestionPage, showListQuestion);
}
/**
 * 显示试题信息
 * 
 * @param list
 */
function showListQuestion(list) {
	var node = "#listData_question";
	$(node).empty();
	papers.listQuestion = list;
	if(list == null || list.length == 0) {
		$(node).append("<li>暂无数据</li>");
		return;
	}
	for(var i = 0; i < list.length; i++) {
		$(node).append(
			"<li><input type='checkbox' value='" + list[i].questionId +
			"' id='qi_" + list[i].questionId +
			"' class='chkQuestionItem' name='" + i +
			"'><label for='qi_" + list[i].questionId + "'>" +
			list[i].subject + "</label></li>");
		if(papers.questionIds[list[i].questionId] == "1") {
			$("#qi_" + list[i].questionId).prop("checked", true);
		}
	}

}
/**
 * 根据试卷id查询试题信息
 * 
 * @param id
 */
function findPapersQuestionByPapersId(id) {
	toolAction
		.baseXHR("Papers/findPapersQuestionByPapersId", "papersId=" + id)
		.done(
			function(data) {
				var list = data.baseModel.data;
				var scoreSum = 0; // 总分
				if(list != null && list.length > 0) {
					for(var i = 0; i < list.length; i++) {
						var li = $("<li></li>");
						li
							.append("<label id='qil_" +
								list[i].questionId + "'>" +
								list[i].question.subject +
								"</label>");
						li
							.append("<input name='questionIds' type='hidden' value='" +
								list[i].questionId + "'>");
						li
							.append("<input name='scores' type='hidden' value='" +
								list[i].score + "'>");
						li.append("<label class='scores'>(" +
							list[i].score + "分)</label>");
						scoreSum += list[i].score;
						if(list[i].question.classes == 2) { // 判断题
							li
								.append("<span class='answer'>" +
									(list[i].question.answer == 0 ? "正确" :
										"错误") + "</span>");
						} else {
							li.append("<span class='answer'>" +
								list[i].question.answer +
								"</span>");
						}

						var options = $("<ul class='questionOption'></ul>");
						if(list[i].listOption != null) {
							for(var j = 0; j < list[i].listOption.length; j++) {
								options
									.append("<li>" +
										list[i].question.listOption[j].optionCode +
										"." +
										list[i].question.listOption[j].optionContent +
										"</li>");
							}
						}
						li.append(options);
						$("#listQuest_" + list[i].question.classes)
							.append(li);
						papers.questionIds[list[i].questionId] = "1";
					}
				}
				$("#scoreSum_view").html(scoreSum); // 总分
			});
}

function showTypeDialog() {
	$("#typeParentDialog").dialog("open");
}

function showTypeDialogQuestion() {
	$("#typeParentDialog_question").dialog("open");
}
/**
 * 显示随机试题生成框
 * 
 * @returns {Boolean}
 */
function showAddQuestionRandom() {
	/*if ($("#typeId_view input").length == 0
			|| $("#typeId_view input").val() == "") {
		alert("请分类后再进行添加随机试题");
		return false;
	}*/
	$("#questionRandomDialog").dialog("open");
}
/**
 * 生成随机试卷
 * 
 * @param map
 */
function setRamdomQuestion(map) {
	$("#listQuest_0,#listQuest_1,#listQuest_2,#listQuest_3,#listQuest_4")
		.empty();
	papers.questionIds = {};
	var listRadio = map.listRadio;
	var listCheckbox = map.listCheckbox;
	var listBoolean = map.listBoolean;
	var listText = map.listText;
	var listTextarea = map.listTextarea;
	// 单选题
	if($("#randScore_0").val() > 0 && listRadio.length > 0) {
		showListQuestion(listRadio);
		$("#classes_search_question").val("0");
		$("#srore_papersQuestion").val($("#randScore_0").val());
		$("#listData_question .chkQuestionItem").click();
	}
	// 多选题
	if($("#randScore_1").val() > 0 && listCheckbox.length > 0) {
		showListQuestion(listCheckbox);
		$("#classes_search_question").val("1");
		$("#srore_papersQuestion").val($("#randScore_1").val());
		$("#listData_question .chkQuestionItem").click();
	}
	// 判断题
	if($("#randScore_2").val() > 0 && listBoolean.length > 0) {
		showListQuestion(listBoolean);
		$("#classes_search_question").val("2");
		$("#srore_papersQuestion").val($("#randScore_2").val());
		$("#listData_question .chkQuestionItem").click();
	}
	// 填空题
	if($("#randScore_3").val() > 0 && listText.length > 0) {
		showListQuestion(listText);
		$("#classes_search_question").val("3");
		$("#srore_papersQuestion").val($("#randScore_3").val());
		$("#listData_question .chkQuestionItem").click();
	}
	// 解答题
	if($("#randScore_4").val() > 0 && listTextarea.length > 0) {
		showListQuestion(listTextarea);
		$("#classes_search_question").val("4");
		$("#srore_papersQuestion").val($("#randScore_4").val());
		$("#listData_question .chkQuestionItem").click();
	}
}